#!/usr/bin/env python

import web
import os
import config
from log import log
from base import adminAction

'''
Admin controller: producing login views.
'''
class loginAction(adminAction):
    def __init__(self, name = 'Login'):
        adminAction.__init__(self, name, chkLogin=False, chkInstall=False)

    def index(self):
        return self.display('login')

    def check(self):
        from web import form
        validList=(
            form.Textbox("username", form.regexp(r".{3,20}$", 'User name: 3-20 chars')),
            form.Password("password", form.regexp(r".{3,20}$", 'Password: 3-20 chars')),
        )

        if not self.validates(validList):
            return self.error(self.errorMessage)

        inputData = self.getInput()
        if config.ADMIN_USERNAME == inputData['username'] and config.ADMIN_PASSWORD == inputData['password']:
            userData={'username':inputData['username']}
            self.setLogin(userData)
            return self.success(msg='Login successfully', url='/admin/')
        else:
            return self.error('Username or password not correct', url='/admin/login/')


    def GET(self, name):
        # Login: index page
        if not name:
            return self.index()
        # Login: page not found
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'check':
            return self.check()
        else:
            return self.notFound()
